package LandR.imageAuthCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 用于处理图形验证码的接口
 */
@WebServlet("/ImageCode")
public class ImageCode extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStreamReader insr = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
        StringBuilder result = new StringBuilder();
        int respInt = insr.read();
        while (respInt != -1) { // 读取请求数据
            result.append((char) respInt);
            respInt = insr.read();
        }

        String inCode = result.toString();
        String temp = inCode.substring(1, 5);

        System.out.println("前端传递的验证图形验证码的数据为:" + temp);

        //得到用户数据，并将数据转换为小写字符
        String valiCode = request.getSession().getAttribute("valiCode").toString();
        System.out.println("后端生成的验证码是：" + valiCode);
        //得到之前随机生成的字符串
        response.setContentType("text/html;charset = utf-8");
        //转码
        PrintWriter out = response.getWriter();

        if (temp.equals(valiCode)) {
            System.out.println("图形验证码验证成功！");
            out.println("验证成功！");
        } else {
            System.out.println("图形验证码验证失败！");
            out.print("验证失败！");
        }
    }
}
